import React, { Component } from 'react';
import "./css/index.css"
class Index extends Component {
    constructor(props){
        super(props);
        this.state  = {
            msg:"",
            list:[],
            checkbox:false,
            done:[]
        }
    }
    render() {
        const ListItem = this.state.list.map((item,index)=>{
            return (
            <div key={item.msg}>
              <input type="checkbox" checked={item.checked} onChange={this.ListChecked.bind(this,item.msg)}/>
              <span>{index+1}</span>{item.msg} 
              <p className="title" onClick={this.handleClick.bind(this,index)}>删除</p >
            </div>)
        })
        const done =this.state.done.map((item,index)=>{
          return (
          <div key={item.msg}> 
            <input type="checkbox" checked={item.checked} onChange={this.ListChecked.bind(this,item.msg)}/>
            <span>{index+1}</span>{item.msg}
            <p className="title" onClick={this.DoneDelete.bind(this,index)}>删除</p>
          </div>)
      })
        return (
            <div>
                <h1>todoList</h1>
                <input type="text" value={this.state.msg} 
               onChange={this.handleChange}
               onKeyUp={this.handleEnter} />
               <h2>未完成 {this.state.list.length}</h2>
                <div>{ListItem}</div>
                <h2>已完成 {this.state.done.length}</h2>
                <div>{done}</div>
            </div>
        );
    }
    handleChange=(event)=>{
      this.setState({
          msg:event.target.value
      })
  }
  handleEnter=(event)=>{
    // console.log(event);
    if(event.keyCode===13){
        var list =this.state.list
        var msg =this.state.msg
        list.push({msg,checked:false})
        this.setState({
            list,
            msg:""
        })
        localStorage.setItem("list",JSON.stringify(list))
      }
    }
    handleClick=(index)=>{
      let list =this.state.list
      list.splice(index,1)
      this.setState({
          list
      })
      localStorage.setItem("list",JSON.stringify(list))
    }
    ListChecked(msg){
      var {list,done} =this.state
      list =list.filter(item=>{
          if(item.msg === msg){
              item.checked =!item.checked
              done.push(item)
          }
          return item.checked ===false
      })
      this.setState({list,done})
        localStorage.setItem("list",JSON.stringify(list))
        localStorage.setItem("done",JSON.stringify(done))
    }
    DoneDelete(index){
      let done =this.state.done
      done.splice(index,1)
      this.setState({
          done
      })
      localStorage.setItem("done",JSON.stringify(done))
  }
  componentDidMount(){
    let list =localStorage.getItem("list")
    let done =localStorage.getItem("done")
    this.setState({
      list:JSON.parse(list),
      done:JSON.parse(done)
    })
  }
}

export default Index;
